<template>
	<view class="container">
		<view class="section-title">资质证书上传</view>
		<view class="section-tips">
			<text class="tip-text">上传您的资质证书以完成身份认证</text>
			<text class="tip-text">审核通过后，认证信息将显示在个人资料中</text>
		</view>
		
		<!-- 表单区域 -->
		<view class="form-container">
			<form @submit="submitForm">
				<!-- 角色选择 -->
				<view class="form-item">
					<text class="form-label">申请角色</text>
					<picker class="form-picker" @change="bindRoleChange" :value="roleIndex" :range="roleOptions">
						<view class="picker-value">
							<text>{{roleOptions[roleIndex] || '请选择申请角色'}}</text>
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>
				
				<!-- 姓名 -->
				<view class="form-item">
					<text class="form-label">姓名</text>
					<input class="form-input" type="text" v-model="formData.real_name" placeholder="请输入您的真实姓名" />
				</view>
				
				<!-- 性别 -->
				<view class="form-item">
					<text class="form-label">性别</text>
					<picker class="form-picker" @change="bindGenderChange" :value="genderIndex" :range="genderOptions">
						<view class="picker-value">
							<text>{{genderOptions[genderIndex] || '请选择性别'}}</text>
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>
				
				<!-- 年龄 -->
				<view class="form-item">
					<text class="form-label">年龄</text>
					<input class="form-input" type="number" v-model="formData.age" placeholder="请输入您的年龄" />
				</view>
				
				<!-- 裁判等级 (仅裁判员需要) -->
				<view class="form-item" v-if="formData.role_type === 1">
					<text class="form-label">裁判等级（针对裁判员身份）</text>
					<picker class="form-picker" @change="bindLevelChange" :value="levelIndex" :range="levelOptions">
						<view class="picker-value">
							<text>{{levelOptions[levelIndex] || '请选择裁判等级'}}</text>
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>
				
				<!-- 所属协会 -->
				<view class="form-item">
					<text class="form-label">所属协会</text>
					<input class="form-input" type="text" v-model="formData.register_organization" placeholder="请输入所属协会" />
				</view>
				
				<!-- 证书认证日期 -->
				<view class="form-item">
					<text class="form-label">证书认证日期</text>
					<picker class="form-picker" mode="date" @change="bindDateChange" :value="formData.register_date">
						<view class="picker-value">
							<text>{{formData.register_date || '请选择证书认证日期'}}</text>
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view>
				
				<!-- 证书编号（非管理员） -->
				<view class="form-item" v-if="formData.role_type !== 4">
					<text class="form-label">证书编号（没有编号可填原因）</text>
					<input class="form-input" type="text" v-model="formData.certificate_no" placeholder="请输入证书编号，没有编号请填写原因" />
				</view>
				
				<!-- 工作职务（仅管理员） -->
				<view class="form-item" v-if="formData.role_type === 4">
					<text class="form-label">工作职务</text>
					<input class="form-input" type="text" v-model="formData.certificate_no" placeholder="请输入您的工作职务" />
				</view>
				
				<!-- 证书图片上传 -->
				<view class="form-item upload-item">
					<text class="form-label">证书图片</text>
					<view class="upload-container">
						<view class="upload-box" @click="chooseImage" v-if="!formData.certificate_image">
							<text class="upload-icon">+</text>
							<text class="upload-text">上传图片</text>
						</view>
						<view class="image-preview" v-else>
							<image :src="formData.certificate_image" mode="aspectFit" class="preview-image" @click="previewImage"></image>
							<text class="remove-image" @click="removeImage">×</text>
						</view>
					</view>
					<text class="upload-tip">支持jpg、png、jpeg格式，大小不超过5MB</text>
				</view>
				
				<!-- 备注信息 -->
				<view class="form-item">
					<text class="form-label">备注信息</text>
					<textarea class="form-textarea" v-model="formData.remarks" placeholder="可添加其他说明信息（选填）" />
				</view>
				
				<!-- 提交按钮 -->
				<view class="form-actions">
					<button class="submit-btn" type="button" :disabled="submitDisabled || submitting" @click="submitForm">
						{{submitting ? '提交中...' : '提交认证'}}
					</button>
				</view>
			</form>
		</view>
	</view>
</template>

<script>
	import { getToken } from '../../utils/tokenManager.js';
	
	export default {
		data() {
			return {
				formData: {
					real_name: '',
					gender: '', // 性别
					age: '', // 年龄
					certificate_no: '',
					register_organization: '',
					level: 0, // 证书等级
					register_date: '',
					certificate_image: '', // 证书图片临时路径
					remarks: '',
					role_type: 0 // 申请角色类型：1-裁判员，3-裁判监督，4-管理员
				},
				levelOptions: ['请选择等级', '三级', '二级', '一级', '预备国家级', '国家级', '国际级'],
				levelIndex: 0,
				roleOptions: ['请选择角色', '裁判员', '裁判监督', '管理员'],
				roleIndex: 0,
				genderOptions: ['请选择性别', '男', '女'],
				genderIndex: 0,
				submitting: false
			}
		},
		computed: {
			submitDisabled() {
				// 检查必填字段
				const { real_name, gender, age, certificate_no, register_organization, register_date, certificate_image, role_type } = this.formData;
				
				// 检查角色选择
				if (!role_type) {
					return true;
				}
				
				// 基础必填字段验证
				if (!real_name || !gender || !age || !certificate_no || !register_organization || !register_date || !certificate_image) {
					return true;
				}
				
				// 裁判员需要选择等级
				if (role_type === 1 && this.formData.level === 0) {
					return true;
				}
				
				return false;
			}
		},
		onLoad() {
			// 检查登录状态
			this.checkLogin();
		},
		methods: {
			// 检查登录状态
			checkLogin() {
				const token = getToken();
				if (!token) {
					// 未登录，跳转到登录页
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/login/login?from=credential-upload'
						});
					}, 100);
					return;
				}
				
				// token有效，获取用户信息
				const userInfoStr = uni.getStorageSync('userInfo');
				if (userInfoStr) {
					try {
						const userInfo = JSON.parse(userInfoStr);
						console.log('用户信息:', userInfo);
						
						// 如果已有姓名信息则自动填充
						if (userInfo.real_name) {
							this.formData.real_name = userInfo.real_name;
						}
					} catch (e) {
						console.error('解析用户信息失败', e);
						// 解析失败也跳转登录
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/login/login?from=credential-upload'
							});
						}, 100);
					}
				} else {
					// 无用户信息，跳转登录
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/login/login?from=credential-upload'
						});
					}, 100);
				}
			},
			
			// 角色选择变化
			bindRoleChange(e) {
				this.roleIndex = parseInt(e.detail.value);
				// 角色值: 0-未选择, 1-裁判员, 2-裁判监督, 3-管理员
				if (this.roleIndex === 1) {
					this.formData.role_type = 1; // 裁判员
				} else if (this.roleIndex === 2) {
					this.formData.role_type = 3; // 裁判监督
				} else if (this.roleIndex === 3) {
					this.formData.role_type = 4; // 管理员
				} else {
					this.formData.role_type = 0; // 未选择
				}
			},
			
			// 等级选择变化
			bindLevelChange(e) {
				this.levelIndex = parseInt(e.detail.value);
				// 等级值: 0-未选择, 1-三级, 2-二级, 3-一级, 4-预备国家级, 5-国家级, 6-国际级
				this.formData.level = this.levelIndex;
			},
			
			// 注册日期选择变化
			bindDateChange(e) {
				this.formData.register_date = e.detail.value;
			},
			
			// 性别选择变化
			bindGenderChange(e) {
				this.genderIndex = parseInt(e.detail.value);
				// 性别值: 0-未选择, 1-男, 2-女
				if (this.genderIndex === 1) {
					this.formData.gender = '男';
				} else if (this.genderIndex === 2) {
					this.formData.gender = '女';
				} else {
					this.formData.gender = '';
				}
			},
			
			// 选择图片
			chooseImage() {
				uni.chooseImage({
					count: 1, // 默认9
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
					sourceType: ['album', 'camera'], // 从相册选择或使用相机
					success: (res) => {
						// 检查图片大小
						const tempFilePath = res.tempFilePaths[0];
						// 使用新的API替代即将废弃的wx.getFileInfo
						const fsm = wx.getFileSystemManager();
						fsm.getFileInfo({
							filePath: tempFilePath,
							success: (fileInfo) => {
								const fileSize = fileInfo.size / 1024 / 1024; // 转换为MB
								if (fileSize > 5) {
									uni.showToast({
										title: '图片大小不能超过5MB',
										icon: 'none'
									});
									return;
								}
								
								// 设置图片临时路径
								this.formData.certificate_image = tempFilePath;
							}
						});
					}
				});
			},
			
			// 预览图片
			previewImage() {
				if (!this.formData.certificate_image) return;
				uni.previewImage({
					urls: [this.formData.certificate_image],
					current: this.formData.certificate_image,
					indicator: 'number',
					loop: false
				});
			},
			
			// 移除图片
			removeImage() {
				this.formData.certificate_image = '';
			},
			
			// 提交表单
			async submitForm() {
				if (this.submitting) {
					return;
				}
				
				// 表单验证
				if (!this.formData.real_name) {
					this.showToast('请输入您的真实姓名');
					return;
				}
				
				if (!this.formData.role_type) {
					this.showToast('请选择申请角色');
					return;
				}
				
				if (!this.formData.gender) {
					this.showToast('请选择性别');
					return;
				}
				
				if (!this.formData.age) {
					this.showToast('请输入年龄');
					return;
				}
				
				if (!this.formData.certificate_no) {
					this.showToast('请输入证书编号');
					return;
				}
				
				if (this.formData.role_type === 1 && !this.formData.level) {
					this.showToast('请选择裁判等级');
					return;
				}
				
				if (!this.formData.register_organization) {
					this.showToast('请输入所属协会');
					return;
				}
				
				if (!this.formData.register_date) {
					this.showToast('请选择证书认证日期');
					return;
				}
				
				// 验证上传证书图片
				if (!this.formData.certificate_image) {
					this.showToast('请上传证书图片');
					return;
				}
				
				// 开始提交
				this.submitting = true;
				uni.showLoading({
					title: '正在提交...'
				});
				
				// 再次验证token是否有效
				const token = getToken();
				if (!token) {
					uni.hideLoading();
					
					uni.showToast({
						title: '登录已过期，请重新登录',
						icon: 'none',
						duration: 1500
					});
					
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/login/login?from=credential-upload'
						});
					}, 1500);
					return;
				}
				
				// 转换日期格式为时间戳
				const formDataSubmit = {
					...this.formData,
					register_date: new Date(this.formData.register_date).getTime()
				};
				
				// 确保角色名称与角色类型对应
				if (formDataSubmit.role_type === 1) {
					formDataSubmit.role_name = '裁判员';
				} else if (formDataSubmit.role_type === 3) {
					formDataSubmit.role_name = '裁判监督';
				} else if (formDataSubmit.role_type === 4) {
					formDataSubmit.role_name = '管理员';
				} else {
					formDataSubmit.role_name = '';
				}
				
				console.log('提交认证信息:', formDataSubmit);
				
				// 调用上传认证接口
				try {
					const credentialService = uniCloud.importObject('credential-service');
					const res = await credentialService.uploadCertificate({
						token: token,
						credential: formDataSubmit,
						certificateType: this.getCertificateType(formDataSubmit.role_type)
					});
					
					uni.hideLoading();
					
					console.log('上传结果:', res);
					if (res && res.code === 0) {
						// 更新用户的认证状态为"审核中"(pending)
						const userInfo = JSON.parse(uni.getStorageSync('userInfo') || '{}');
						userInfo.credential_status = 'pending';
						// 同时更新申请的角色类型，用于个人中心显示
						userInfo.pending_role_type = formDataSubmit.role_type;
						uni.setStorageSync('userInfo', JSON.stringify(userInfo));
						
						// 成功提示
						uni.showToast({
							title: '提交成功，请等待审核',
							icon: 'success',
							duration: 1500
						});
						
						// 提交成功后跳转到个人中心
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/my/my'
							});
						}, 1500);
						
						this.submitting = false;
					} else {
						// 失败提示
						let errorMsg = '提交失败，请重试';
						if (res && res.message) {
							errorMsg = res.message;
						}
						
						uni.showToast({
							title: errorMsg,
							icon: 'none',
							duration: 2000
						});
						
						this.submitting = false;
					}
				} catch (err) {
					uni.hideLoading();
					console.error('上传失败:', err);
					
					// 检查token是否过期或用户未认证
					if (err.errCode === 'TOKEN_INVALID' || 
						(err.message && (err.message.includes('未登录') || err.message.includes('登录已过期'))) ||
						(err.code === 401) ||
						(res && res.code === 401) ||
						(res && res.code === -1 && res.message && res.message.includes('未登录'))) {
						uni.showToast({
							title: '登录已过期，请重新登录',
							icon: 'none',
							duration: 1500
						});
						
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/login/login?from=credential-upload'
							});
						}, 1500);
					} else {
						uni.showModal({
							title: '提交失败',
							content: '系统错误，请稍后再试或联系客服',
							showCancel: false
						});
						
						this.submitting = false;
					}
				}
			},
			
			// 获取证书类型
			getCertificateType(roleType) {
				switch(roleType) {
					case 1: return 'referee'; // 裁判员
					case 3: return 'supervisor'; // 裁判监督
					case 4: return 'admin'; // 管理员
					default: return 'referee';
				}
			},
			
			// 显示提示
			showToast(title) {
				uni.showToast({
					title: title,
					icon: 'none'
				});
			}
		}
	}
</script>

<style>
	.container {
		padding: 30rpx;
	}
	
	.section-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}
	
	.section-tips {
		background-color: #f5f7fa;
		padding: 20rpx;
		border-radius: 10rpx;
		margin-bottom: 30rpx;
	}
	
	.tip-text {
		display: block;
		font-size: 24rpx;
		color: #666;
		line-height: 1.5;
	}
	
	.form-container {
		background-color: #fff;
		border-radius: 10rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.form-item {
		margin-bottom: 30rpx;
	}
	
	.form-label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 15rpx;
	}
	
	.form-input {
		width: 100%;
		height: 80rpx;
		background-color: #f5f7fa;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		box-sizing: border-box;
	}
	
	.form-picker {
		width: 100%;
	}
	
	.picker-value {
		width: 100%;
		height: 80rpx;
		background-color: #f5f7fa;
		border-radius: 10rpx;
		padding: 0 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;
	}
	
	.picker-arrow {
		font-size: 24rpx;
		color: #999;
	}
	
	.form-textarea {
		width: 100%;
		height: 200rpx;
		background-color: #f5f7fa;
		border-radius: 10rpx;
		padding: 20rpx;
		font-size: 28rpx;
		box-sizing: border-box;
	}
	
	.upload-item {
		margin-bottom: 40rpx;
	}
	
	.upload-container {
		width: 100%;
		margin-bottom: 10rpx;
	}
	
	.upload-box {
		width: 200rpx;
		height: 200rpx;
		background-color: #f5f7fa;
		border-radius: 10rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	
	.upload-icon {
		font-size: 60rpx;
		color: #999;
		margin-bottom: 10rpx;
	}
	
	.upload-text {
		font-size: 26rpx;
		color: #999;
	}
	
	.image-preview {
		position: relative;
		width: 300rpx;
		height: 300rpx;
	}
	
	.preview-image {
		width: 100%;
		height: 100%;
		border-radius: 10rpx;
	}
	
	.remove-image {
		position: absolute;
		top: -20rpx;
		right: -20rpx;
		width: 40rpx;
		height: 40rpx;
		background-color: #ff4d4f;
		color: #fff;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
	}
	
	.upload-tip {
		font-size: 24rpx;
		color: #999;
	}
	
	.form-actions {
		margin-top: 50rpx;
		padding-bottom: 50rpx;
	}
	
	.submit-btn {
		width: 100%;
		height: 90rpx;
		background-color: #1BAE76;
		color: #fff;
		border-radius: 10rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
	}
	
	.submit-btn[disabled] {
		background-color: #ccc;
	}
</style> 